package com.example.qrwebview

import android.os.Bundle
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
import com.example.qrwebview.ui.theme.QRWebViewTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            QRWebViewTheme {
                // A surface container using the 'background' color from the theme
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
                    Greeting()
                }
            }
        }

    }
}

@Composable
fun Greeting() {
    AndroidView(factory = { context -> WebView(context).apply {
        //h5代码文件放入assets 文件夹下面
        settings.setJavaScriptEnabled(true)
        settings.setUseWideViewPort(true)
        settings.setLoadWithOverviewMode(true)
        settings.setSupportZoom(false)
        settings.setBuiltInZoomControls(false)
        settings.setDisplayZoomControls(false)
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE)
        settings.setAllowFileAccess(true)
        settings.setAllowUniversalAccessFromFileURLs(true)
        settings.setAllowFileAccessFromFileURLs(true)
        settings.setJavaScriptCanOpenWindowsAutomatically(true)
        settings.setDefaultTextEncodingName("utf-8")
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW)
        settings.setDomStorageEnabled(true)
        settings.setUserAgentString(settings.getUserAgentString() + "ZDAN")
        settings.mediaPlaybackRequiresUserGesture = false //设置音频自动播放
        WebView.setWebContentsDebuggingEnabled(true)
        webChromeClient = myWebChromeClient()
        loadUrl("file:///android_asset/dist/index.html")

    } })
}

class myWebChromeClient:WebChromeClient(){
    //重写当前方法，关键部分
    override fun onPermissionRequest(request: PermissionRequest?) {
        request?.grant(request.resources)
    }
}

@Preview
@Composable
fun show(){
    Greeting()
}


